
var crypto = require("crypto"); // node模块

//加密函数 data 需要加密的字段
function aesEncrypt(data, key) {
    const cipher = crypto.createCipher('aes192', key);
    var crypted = cipher.update(data, 'utf8', 'hex');
    crypted += cipher.final('hex');
    return crypted;
}


//解密
function aesDecrypt(encrypted, key) {
    const decipher = crypto.createDecipher('aes192', key);
    var decrypted = decipher.update(encrypted, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;
}
const keys = "kfdjg";
exports.aesEncrypt = aesEncrypt; // 加密
exports.aesDecrypt = aesDecrypt;// 解密
exports.keys = keys;//密钥



// 检测后端session token 是否存在是否登录
// req.headers.AUTH_TOKEN/Authorization把token 传递过来
// **后端需要处理的逻辑
// 1.如果req.headers 没有token 直接判断token不存在,请马上登录
// 2.前端req.headers 有token ，但是后端的session 没有存储token token过期或者失效
// 3.前端req.headers 有token, 后端session 也有token 但是不匹配 token不匹配
exports.checkToken = function (req, res, next) {
    // console.log(req.path);
    if (req.path !== "/vant/login" && req.path !== "/vant/register" && req.path !== "/vant/cities" && req.path !== "/vant/details" && req.path !== "/vant/goodlist") {
        // 前端的token
        // console.log(req.headers);//发现全改成小写的
        const client_token = req.headers['authorization'];
        // console.log(req.session);// 后端的token(跨域问题: 直接访问不到session)
        const server_token = req.session.token;
        // 代理之后才可以取到,登录之后存在服务端的,因此一改后台代码就失去权限
        // const server_token = req.headers.authorization; 
        // const user = aesDecrypt(req.headers.authorization, keys)
        // console.log(req.session)
        // console.log(client_token, server_token)
        // console.log(req.session.cookie.token)
        // console.log(client_token == server_token, client_token === server_token)
        if (client_token) {
            if (server_token) {
                if (client_token === server_token) {
                    // 原理是配置中间件放在路由的前面,只有匹配了才能next()
                    // 或者对登录注册开了口子
                    next();
                } else {
                    // 不等
                    res.json({
                        code: 500,
                        msg: "token不匹配",
                        result: 0
                    });
                }
            } else {
                // 无服务端token
                res.json({
                    code: 500,
                    msg: "token过期或者失效",
                    result: 0
                });
            }
        } else {
            // 无客户端token
            res.json({
                code: 500,
                msg: "token不存在,请登录",
                result: 0
            });
        }
    } else {
        // 放行 
        next();
    }
}
